<template>
  <el-dialog
    v-model="dialogVisible"
    :title="`第${numberSections}节课`"
    width="80%"
    :before-close="handleClose"
  >
    <div class="dialog-body">
      <div class="grids gridColumns3" style="width: 90%; margin-bottom: 30px">
        <div>
          <div class="row">
            <span class="bold">排课日期</span>
            ：{{ info.date }}（{{ getWeekday(info.date) }}）
          </div>
          <div class="row">
            <span class="bold">授课老师</span>
            ：{{ info.teachingTeacher }}
          </div>
          <div class="row">
            <span class="bold">班级人数：</span>
            {{ count }} / {{ tableParams.total }}
          </div>
        </div>

        <div>
          <div class="row">
            <span class="bold">
              <span class="bold">上课时间</span>
            </span>
            ：{{ info.classStartTime }} - {{ info.classEndTime }}
          </div>
          <div class="row flex">
            <span class="bold">授课地点</span>
            ：<dictSelect
              readonly="1"
              v-model="info.classAddress"
              dictCode="teaching_location"
            ></dictSelect>
          </div>
          <div class="row">
            <span class="bold">单位课时</span>
            ：{{ info.unitClassHours }}
          </div>
        </div>

        <div>
          <div class="flex row">
            <span class="bold">关联课程：</span>
            <courseQuery v-model="info.curriculumId" readonly="1"></courseQuery>
          </div>
          <div class="flex row">
            <span class="bold">授课内容：</span>
            {{ info.teachingContent }}
          </div>
        </div>
      </div>

      <div class="actionBtn">
        <el-button
          color="#333333"
          plain
          :disabled="!selectArr.length"
          @click="setStatus(1)"
          >到课</el-button
        >
        <el-button
          color="#BD3124"
          plain
          :disabled="!selectArr.length"
          @click="setStatus(2)"
          >未到</el-button
        >
        <el-button
          color="#0F40F5"
          plain
          :disabled="!selectArr.length"
          @click="setStatus(3)"
          >请假</el-button
        >
        <el-button
          type="primary"
          @click="canEdit = !canEdit"
          v-if="info.signInComplete && info.signInComplete == 1"
        >
          修改签到状态
        </el-button>
      </div>

      <el-table
        :data="tableParams.rows"
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
      >
        <el-table-column
          type="selection"
          width="55"
          fixed="left"
          :selectable="selectable"
        />
        <el-table-column label="状态" prop="name" width="60" fixed="left">
          <template #default="scope">
            <div v-if="isSuspensionClass(scope.row)" style="color: #8530f5">
              停课
            </div>
            <div v-else class="status-icon">
              <img src="@/assets/images/checkIcon.png" alt="" />
            </div>
          </template>
        </el-table-column>
        <el-table-column type="index" width="50" label="序号" fixed="left" />
        <el-table-column
          label="姓名"
          prop="user_info.baseInfo.name"
          width="80"
          fixed="left"
        >
          <template #default="scope">
            <div v-if="scope.row.source && scope.row.source == 'file'">
              {{ scope.row.user_data.name }}
            </div>
            <div v-else>{{ scope.row.user_info.baseInfo.name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="性别" prop="name" width="75">
          <template #default="scope">
            <div v-if="scope.row.source && scope.row.source == 'file'">
              {{ getGenderByIdCard(scope.row.user_data.identityCard) }}
            </div>
            <div v-else>
              {{ getGenderByIdCard(scope.row.user_info.baseInfo.identityCard) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="user_info.baseInfo.mobile"
          label="联系方式"
          width="150"
        >
          <template #default="scope">
            <div v-if="scope.row.source && scope.row.source == 'file'">
              {{ scope.row.user_data.mobile }}
            </div>
            <div v-else>{{ scope.row.user_info.baseInfo.mobile }}</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="user_info.baseInfo.identityCard"
          label="身份证号"
          width="180"
        >
          <template #default="scope">
            <div v-if="scope.row.source && scope.row.source == 'file'">
              {{ scope.row.user_data.identityCard }}
            </div>
            <div v-else>{{ scope.row.user_info.baseInfo.identityCard }}</div>
          </template>
        </el-table-column>
        <el-table-column label="报名所属" width="150">
          <template #default="scope">
            <div v-if="scope.row.source && scope.row.source == 'file'">
              {{ affiliation_format(scope.row.user_data.affiliation) }}
            </div>
            <div v-else>
              {{ affiliation_format(scope.row.user_info.baseInfo.affiliation) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="user_info.baseInfo.enterprise"
          label="所在企业名称"
          width="250"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div v-if="scope.row.source && scope.row.source == 'file'">
              {{ scope.row.user_data.enterprise }}
            </div>
            <div v-else>{{ scope.row.user_info.baseInfo.enterprise }}</div>
          </template>
        </el-table-column>
        <el-table-column label="签到状态" width="80" fixed="right">
          <template #default="scope">
            <div v-if="scope.row.signIn_info.status">
              <div v-if="scope.row.signIn_info.status == 1">到课</div>
              <div
                v-else-if="scope.row.signIn_info.status == 2"
                style="color: #bd3124"
              >
                未到
              </div>
              <div v-else style="color: #0f40f5">请假</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="签到备注" fixed="right" min-width="150">
          <template #default="scope">
            <el-input
              v-model="scope.row.signIn_info.remark"
              placeholder="签到备注"
              @change="remarkChange(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :selectNum="selectArr.length"
        v-if="tableParams['total']"
        :total="tableParams['total']"
        v-model:page="params.pageIndex"
        v-model:limit="params.pageSize"
        @pagination="getInfo"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save" :loading="loading">
          确 认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();
const emit = defineEmits(["fatherMethod"]);

let loading = ref(false);
let dialogVisible = ref(false);
let info = ref({});
let days = ref(0);
let tableParams = ref({});
let params = ref({
  pageIndex: 1,
  pageSize: 50,
  classId: "",
  schedulingId: "",
});
let selectArr = ref([]);
let canEdit = ref(false);
let courseQueryRefWidth = ref(0);
let count = ref(0); //该班次有多少正常状态的学生
let numberSections = ref(0); //第几节课

let colStyle = computed(() => {
  if (courseQueryRefWidth.value) {
    return {
      width: `calc((100% - ${courseQueryRefWidth.value}px - 100px)/2)`,
    };
  }
});

//学生是否是停课状态
function isSuspensionClass(row) {
  let dateStamp = proxy.$utils.getTimeFn(info.value.date);
  let suspensionDateStamp = 0;
  let suspensionClassDate;
  if (row.userState == 0) {
    suspensionClassDate = row.suspensionClassDate;
    suspensionDateStamp = proxy.$utils.getTimeFn(suspensionClassDate);
  }
  return row.userState == 0 && dateStamp >= suspensionDateStamp;
}

async function save() {
  try {
    loading.value = true;

    //如果已经签到完成了
    if (info.value.signInComplete && info.value.signInComplete == 1) {
    } else {
      let canSave = await getSignInNum();
      if (!canSave)
        return proxy.$utils.showToast(
          "该班次未签到完整，请选择未签到学生后再保存",
          0
        );
    }

    //有多少人到课了
    let toClassStudent = await queryToClassNum();

    //计算百分比
    let percentageComplete = (toClassStudent / count.value) * 100;
    let signInRate = Math.round(percentageComplete * 100) / 100;

    await proxy.$apis.teachingScheduleData({
      type: "update",
      data: {
        _id: info.value._id,
        signInComplete: 1, //该班次点名完成
        nameCallingTime: Date.now(), //点名完成时间
        //签到情况
        checkInStatus: `${toClassStudent}/${count.value}`,
        //签到率
        signInRate: signInRate + "%",
      },
    });
    proxy.$utils.showToast("保存成功");
    handleClose();
  } catch (error) {
    console.log("签到", error);
  } finally {
    loading.value = false;
  }
}

//计算百分比
function calculatePercentage(partialValue, totalValue) {
  if (totalValue === 0 || isNaN(partialValue) || isNaN(totalValue)) {
    return 0; // 防止除以0错误，并确保输入值是数字
  }
  return (partialValue / totalValue) * 100;
}

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: User;
  rowIndex: number;
}) => {
  if (row.source && row.source == "file") {
    return "warning-row";
  }
  return "";
};

//获取排期节数
async function queryLessonNum() {
  numberSections.value = await proxy.$apis.teachingScheduleData({
    type: "queryLessonNum",
    data: { classId: info.value.classId, _id: info.value._id },
  });
}

//到课人数
async function queryToClassNum() {
  let toClassStudent = await proxy.$apis.classNameCalling({
    type: "query",
    data: {
      classId: info.value.classId,
      schedulingId: info.value._id,
      status: 1,
    },
  });
  return toClassStudent.length;
}

async function open(row, num) {
  info.value = { ...row };
  queryLessonNum();
  days.value = num;
  await getInfo();

  count.value = await queryToClassNum();

  //该班次有多少正常状态的学生
  // count.value = await proxy.$apis.classStudent({
  //   type: "classStudentCount",
  //   data: {
  //     classId: info.value.classId,
  //     schedulingId: info.value._id,
  //   },
  // });
  dialogVisible.value = true;
  setCss();
}

function setCss() {
  nextTick(() => {
    if (proxy.$refs.courseQueryRef) {
      courseQueryRefWidth.value = proxy.$refs.courseQueryRef.offsetWidth;
    }
  });
}

//该班次已经签到了几个人
async function getSignInNum() {
  return await proxy.$apis.classNameCalling({
    type: "signInStudentsQuery",
    data: { classId: info.value.classId, schedulingId: info.value._id },
  });
}

function handleSelectionChange(e) {
  selectArr.value = e;
}

async function remarkChange(e) {
  //编辑
  if (e.signIn_info.hasOwnProperty("_id")) {
    await proxy.$apis.classNameCalling({
      type: "update",
      data: { remark: e.signIn_info.remark, _id: e.signIn_info._id },
    });
  } else {
    await proxy.$apis.classNameCalling({
      type: "add",
      data: {
        classId: e.classId, //班级id
        schedulingId: e._id, //排期 id
        userId: e.userId, //学生 id
        remark: e.signIn_info.remark, //签到备注
      },
    });
  }
  proxy.$utils.showToast("保存成功");
  getInfo();
}

function selectable(e) {
  if (isSuspensionClass(e)) return false;
  if (canEdit.value) return true;
  //如果该班次已经签到完成，则禁止选择学生
  if (info.value.signInComplete) {
    return false;
  } else if (e.signIn_info.hasOwnProperty("status")) {
    return false;
  } else {
    return true;
  }
}

function affiliation_format(e) {
  if (!e) return "-";
  if (proxy.$utils.isString(e)) {
    return e;
  } else if (proxy.$utils.isArrayOrJsonArray(e)) {
    return e.toString();
  } else {
    return "-";
  }
}

function getGenderByIdCard(idCard) {
  if (!idCard || idCard.length !== 18) {
    throw new Error("Invalid ID card number");
  }
  const sexCode = idCard.charAt(16);
  const gender = parseInt(sexCode, 10) % 2 === 0 ? "女" : "男";
  return gender;
}

async function getInfo() {
  params.value.classId = info.value.classId;
  params.value.schedulingId = info.value._id;
  tableParams.value = await proxy.$apis.classNameCalling({
    type: "studentList",
    data: params.value,
  });
}

function getWeekday(date) {
  const weekdays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
  const weekday = new Date(date).getDay();
  return weekdays[weekday];
}

function handleClose() {
  selectArr.value = [];
  params.value = {
    pageIndex: 1,
    pageSize: 50,
    classId: "",
    schedulingId: "",
  };
  canEdit.value = false;
  emit("fatherMethod"); //列表重新加载
  dialogVisible.value = false;
}

async function setStatus(status) {
  let name;
  switch (status) {
    case 1:
      name = "到课";
      break;
    case 2:
      name = "未到";
      break;
    case 3:
      name = "请假";
      break;
    default:
      break;
  }
  let resp = await proxy.$utils.confirmTips(
    `确定设置选中的学生的状态为${name}吗？`
  );
  if (!resp) return;
  for (let index = 0; index < selectArr.value.length; index++) {
    const element = selectArr.value[index];
    let obj = {
      classId: info.value.classId, //班级id
      schedulingId: info.value._id, //排期 id
      status, //状态 1:到课 2:未到 3:请假
    };
    //线上学员
    if (element.user_info._id) {
      obj["userId"] = element.user_info._id; //学生 id
    } else {
      //线下导入学员
      obj["offlineUserId"] = element.user_data._id;
    }
    await proxy.$apis.classNameCalling({
      type: "setStatus",
      data: obj,
    });
  }
  proxy.$utils.showToast("设置成功");
  getInfo();
}

defineExpose({ open });
</script>

<style lang="scss" scoped>
.row {
  margin-bottom: 10px;
  span {
    flex-shrink: 0;
  }
}
// .row {
//   display: flex;
//   justify-content: space-between;
//   margin-bottom: 15px;
//   .col {
//     text-align: left;
//     flex-shrink: 0;
//   }
// }
.dialog-body {
  max-height: 60vh;
  overflow-y: auto;
}
.actionBtn {
  margin-bottom: 15px;
}
.status-icon {
  width: 15px;
  height: 15px;
  img {
    width: 100%;
    display: block;
  }
}
</style>
